import axios from "axios";

import qs from 'qs';
import { get_token, remove_token, set_token } from '@/utils/token'
import { remove_info } from '@/utils/info'
import { Message } from "element-ui";
import router from "@/router"
import switchEnv from "@/utils/global"
//接口域名
axios.defaults.baseURL = switchEnv().BASE_API;

//get方法：
const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: params })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  })
};

//post方法：
const post = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(data), {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);

      });
  })
};

//post方法：
const post_json = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.post(url, data, {})
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  })
};


// delete请求
const del = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.delete(url, { data })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  })
};


// put请求
const put = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.put(url, qs.stringify(data), {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);

      });
  })
};


// put请求
const put_json = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.put(url, data, {})
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);

      });
  })
};

// 请求拦截器
axios.interceptors.request.use(function (config) {
  let token = get_token();
  if (token) {
    config["headers"]['CAMPUS-TOKEN'] = token;
  }
  return config;
}, err => {
  return Promise.reject(err)
});


// 响应拦截器
axios.interceptors.response.use(function (res) {
  if (res.status !== 200) {
    Message.error("服务器出错");
    return Promise.reject("服务器出错");
  }
  const result = res.data;
  if (result.success) {
    return result.data
  }
  if (result.code === '1002' || result.status === '1003') {
    Message.error(result.tips);
    remove_token();
    remove_info();
    setTimeout(() => {
      location.reload()
    }, 1500)
    return Promise.reject(result.tips);
  }
  Message.error(result.tips);
  return Promise.reject(result.tips);
}, err => {
  //服务器出错
  return Promise.reject("服务器出错");
});

export {
  post,
  get,
  del,
  put,
  post_json,
  put_json
}
